from .text import judge as textj
import os
from requests_async import get,post

judgers={
    'text':textj
}

JUDGER_MODE="NORMAL" # STANDALONE / NORMAL
JUDGEMGMT="127.0.0.1:8080"
HEARTBEAT_URL=f"http://{JUDGEMGMT}/heartbeat/"
REGISTER_URL=f"http://{JUDGEMGMT}/register/"
RESULT_URL=f"http://{JUDGEMGMT}/complete/"
REGISTRY={
    'name':'testjudge1',
    'cap':['text'],
    'addr':"127.0.0.1:80"
}
HEARTBEAT_INTERVAL=4
import asyncio
running=True
async def heartbeat_loop():
    print("Heartbeat: launched.")
    while running:
        try:
            resp=await post(HEARTBEAT_URL,json={"name":REGISTRY["name"]})
            assert resp.status_code==200
        except:
            print("Heartbeat: failed to post heartbeat.")
        await asyncio.sleep(HEARTBEAT_INTERVAL)
    print("Heartbeat: scheduled exit.")

async def register():
    global running
    print(f"Trying to register on {JUDGEMGMT} with {REGISTRY}")
    try:
        resp=await post(REGISTER_URL,json=REGISTRY)
        assert resp.status_code==200
    except:
        print("Failed to register!")
        running=False
        return
    print("Succeed to register.")
    running=True
    asyncio.create_task(heartbeat_loop())

    

from ..models import Submission,Problem
def judge(rid:int):
    sub=Submission.objects.get(real_id=rid)
    pro=Problem.objects.get(problem=sub.problem)
    judgers[pro.type].add_task(rid)

async def start():
    if not os.environ.get("IS_DJANGO_MANAGE"):
        if JUDGER_MODE=="NORMAL":
            await register()
        for i in judgers:
            judgers[i].judger_init()
    else:
        print("Django management script detected, skiping judger initialization.")    

def finish():
    global running
    running=False
    for i in judgers:
        judgers[i].at_exit()
